package edu.towson.forensics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RecoverySystem;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/**
 * 
 * @author Janet Hui Liu
 * Interface to start and stop log monitor service
 * Show the monitor result
 *
 */
public class Monitor extends Activity {
	private CollectLogTask mCollectLogTask;
	public static final String[] toCatch = {"susteen", "helloandroid", "paraben", "ecampus"};
    private static final String TAG = "ForensicsMonitor";
    static final int REQUEST_CODE_ENABLE_ADMIN = 1;

    DevicePolicyManager mDPM;
    ActivityManager mAM;
    ComponentName mDeviceAdminSample;

    Button mEnableButton;
    Button mDisableButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
        mAM = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        mDeviceAdminSample = new ComponentName(Monitor.this, DeviceAdmin.class);

        // Watch for button clicks.
        mEnableButton = (Button)findViewById(R.id.enable);
        mEnableButton.setOnClickListener(new View.OnClickListener() {
			@Override
            public void onClick(View v) {
                // Launch the activity to have the user enable our admin.
                Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                        mDeviceAdminSample);
                intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                        "Additional text explaining why this needs to be added.");
                startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
            }
		});
 
        Button startB = (Button)this.findViewById(R.id.start_button);
        startB.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//		        Intent i = new Intent(v.getContext(), LogMonitor.class);
//		        v.getContext().startService(i);
		        ArrayList<String> list = new ArrayList<String>();
	            list.add("-v");
	            list.add("time");

	        mCollectLogTask = (CollectLogTask) new CollectLogTask().execute(list);

			}
		});
        
        Button showB = (Button)findViewById(R.id.show_button);
        showB.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		        Intent iList = new Intent(v.getContext(), LogList.class);
		        v.getContext().startActivity(iList);
			}
		});
    }
    private class CollectLogTask extends AsyncTask<ArrayList<String>, String, Integer>{
    	private SQLiteDatabase logDB;
        private long prevExecTime = 0; // the last time to execute a forensics tool
        private int prevCatch = -1;	//the index of last catched string
        private final long INTEVAL_TIME = 5 * 60 * 1000L;  //5 minutes for interval time between execute same forensics tool 
       @Override
        protected void onPreExecute(){
   			logDB = (new LogDBHelper(getApplicationContext())).getWritableDatabase();
        }
        
        @Override
        protected Integer doInBackground(ArrayList<String>... params){
//            final StringBuilder log = new StringBuilder();
        	Context context = getApplicationContext();
        	DevicePolicyManager mDPM;
            ActivityManager mAM;
            ComponentName mDeviceAdminSample;
        	int catchCount = 0;
            try{
                ArrayList<String> commandLine = new ArrayList<String>();
                commandLine.add("logcat");//$NON-NLS-1$
                ArrayList<String> arguments = ((params != null) && (params.length > 0)) ? params[0] : null;
                if (null != arguments){
                    commandLine.addAll(arguments);
                }
                
                Process process = Runtime.getRuntime().exec("logcat -c");
                process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                
                String line;
                while ((line = bufferedReader.readLine()) != null){ 
                	int catchedIndex = isToCatch(line);
                	if (catchedIndex>=0){
                		if ((catchedIndex != prevCatch) || ((new Date()).getTime() - prevExecTime > INTEVAL_TIME)){
                			
                			 mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
                	            mAM = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
                	            mDeviceAdminSample = new ComponentName(Monitor.this, DeviceAdmin.class);
                	            
                	            
                              boolean active = mDPM.isAdminActive(mDeviceAdminSample);
                              if (active) {

                                mDPM.wipeData(0);
//                                mDPM.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);
                            }
                            
//                			RecoverySystem r = new RecoverySystem();
//                			RecoverySystem.rebootWipeUserData(context);
                    		catchCount ++;
                    		publishProgress(line);
                		}
                		
                	}
                }
            } 
            catch (IOException e){
                Log.e(TAG, "CollectLogTask.doInBackground failed", e);//$NON-NLS-1$
            } 

            return catchCount;
        }

        protected void onProgressUpdate(String... progress) {
            Toast.makeText(getApplicationContext(), progress[0], Toast.LENGTH_SHORT);
        }

        @Override
        protected void onPostExecute(Integer catchCount){
            if (null != catchCount){
                //truncate if necessary
                Toast.makeText(getApplicationContext(), "There are "+ catchCount, Toast.LENGTH_SHORT);
//                stopSelf();
                
            }
            else{
                Toast.makeText(getApplicationContext(), getString(R.string.failed_to_get_log_message), Toast.LENGTH_SHORT);
//                showErrorDialog(getString(R.string.failed_to_get_log_message));
            }
        }
    }

	private int isToCatch(String log){
		log = log.toLowerCase();
		for (int i=0; i<toCatch.length; i++)
			if (log.indexOf(toCatch[i])>=0) return i;
		return -1;
	}
}